﻿//  --------------------------------
//  Copyright (c) Shawn Duggan. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://www.opensource.org/licenses/ms-pl.html
//  ---------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;

// Taken from the BlueTango library from Shawn Duggan, http://www.shawnduggan.com/?p=54
// original namespace is BlueTango.WPFControls
namespace Elca.MvvmHelpers {
    public class StringToXamlConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            var flowDocument = new FlowDocument();
            if (value != null) {
                var xaml = value.ToString();

                using (var stream = new MemoryStream((new ASCIIEncoding()).GetBytes(xaml))) {
                    var text = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
                    text.Load(stream, DataFormats.Xaml);
                }

            }
            return flowDocument;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            if (value != null) {
                var flowDocument = (FlowDocument)value;
                var range = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
                string xaml;

                using (var stream = new MemoryStream()) {
                    range.Save(stream, TextDataFormat.Xaml.ToString());
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(stream)) {
                        xaml = reader.ReadToEnd();
                    }
                }

                return xaml;
            }
            return value;
        }
    }
}